<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="title" width="650px" destroyOnClose showFooter>
    <Description :column="2" :data="state.record" @register="registerDescription" style="margin-bottom: 15px;"/>
    <Divider>数据权限</Divider>
    <BasicTree
      ref="treeRef"
      checkable
      toolbar
      :toolbarOptions="toolbarOptions"
      :treeData="state.treeData"
      :checkedKeys="state.checkedKeys"
      :selectedKeys="state.selectedKeys"
      :clickRowToExpand="false"
      :checkStrictly="false"
      search
      :defaultExpandLevel="2"
      title="菜单权限"
      @check="onCheck"
      @select="onTreeNodeSelect"
    >
      <template #title="{ title, perms, ruleFlag }">
        <span>{{ title }} </span>
        <span style="padding-left: 5px">{{ perms.split(',').join(' | ') }}</span>
        <Icon v-if="ruleFlag" icon="ant-design:align-left-outlined" style="margin-left: 5px; color: red" />
      </template>
    </BasicTree>

    <!--右下角按钮-->
    <template #footer>
      <PopConfirmButton title="确定放弃编辑？" @confirm="closeDrawer" okText="确定" cancelText="取消">取消</PopConfirmButton>
      <a-button @click="handleSubmit(false)" type="primary" :loading="loading" ghost style="margin-right: 0.8rem">仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="loading">保存并关闭</a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted, toRaw } from "vue"
  import { Divider } from "ant-design-vue"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { BasicTree, TreeItem, TreeActionType, ToolbarEnum } from "/@/components/Tree"
  import { Description, useDescription } from "/@/components/Description/index"
  import { PopConfirmButton } from "/@/components/Button"
  // import { listPermissionTree } from "/@/views/system/menu/menu.api"
  import * as UserApi  from "/@/api/sys/user"
  import { permissionAssignDetailSchema } from "./user.data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Icon } from "/@/components/Icon"
  const { createMessage } = useMessage()
  const toolbarOptions = ref<ToolbarEnum[]>([ToolbarEnum.EXPAND_ALL, ToolbarEnum.UN_EXPAND_ALL, ToolbarEnum.SELECT_ALL, ToolbarEnum.UN_SELECT_ALL])
  const [registerDescription] = useDescription({
    schema: permissionAssignDetailSchema,
    labelStyle: {
      marginLeft: "10px",
      width: "100px",
    },
  })

  const emit = defineEmits(["register"])

  interface State {
    // 树的信息
    treeData: TreeItem[]
    // 树的全部节点信息
    allTreeKeys: any[]
    //树的选择节点信息
    checkedKeys: any[]
    halfCheckedKeys: any[]
    defaultCheckedKeys: any[]
    //树的选中的节点信息
    selectedKeys: any[],
    record: any
  }

  const state = ref<State>({
    treeData: [],
    allTreeKeys: [],
    checkedKeys: [],
    halfCheckedKeys: [],
    defaultCheckedKeys: [],
    selectedKeys: [],
    record: {},
  })
  const stateValue = state.value
  const title = computed(() => `数据授权 【${state.value.record.userName}】`)
  const treeRef = ref<TreeActionType>()
  const loading = ref(false)

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset()
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      console.log('data', data)
      await initMenuPermission(data)
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const initMenuPermission = async (data) => {
    stateValue.record = data.record

    //初始化菜单数据
    // const menuData = await listPermissionTree({})
    // stateValue.treeData = menuData.treeList
    // stateValue.allTreeKeys = menuData.menuList.map((e) => e.id)

    // const permResult = await UserApi.listPermission({ subjectId: stateValue.record.id })
    // stateValue.checkedKeys = permResult.map((e) => e.menuId)
    // stateValue.defaultCheckedKeys = permResult.map((e) => e.menuId)
  }


  function onCheck(o) {
    stateValue.halfCheckedKeys = treeRef.value?.getHalfCheckedKeys() || []
    stateValue.checkedKeys = o.checked ? o.checked : o
  }

  function onTreeNodeSelect(key) {
    if (key && key.length > 0) {
      stateValue.selectedKeys = key
    }
    const menuId = toRaw(stateValue.selectedKeys)[0]
  }

  function reset() {
    stateValue.treeData = []
    stateValue.allTreeKeys = []
    stateValue.checkedKeys = []
    stateValue.defaultCheckedKeys = []
    stateValue.selectedKeys = []
  }

  async function handleSubmit(exit) {
    const { id } = unref(state).record

    let params = {
      userId: id,
      // @ts-ignore
      permissionIds: toRaw(treeRef.value?.getCheckedKeys()).join(","),
      // lastPermissionIds: toRaw(stateValue.defaultCheckedKeys).join(","),
    }

    loading.value = true
    await UserApi.saveUserPermission(params)
    loading.value = false
    exit && closeDrawer()
    createMessage.success("授权成功")
  }
</script>
